package com.zhanglijie.base.other.waitAndNotify;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/6/19 0019 21:23
 */
public class OneProAndConsume {
    private final static Object OBJECT = new Object();
    private static boolean hasRes = false;
    static List list = new ArrayList();
    public static void main(String[] args) throws InterruptedException {
        Thread producer = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    synchronized (OBJECT) {
                        if (hasRes) {
                            try {
                                OBJECT.wait();
                            } catch (Exception e) {
                            }
                        } else {
                            produce();
                            OBJECT.notify();
                            hasRes = true;
                        }
                    }
                }
            }
            private void produce() {
                list.add(new Object());
                System.out.println("produce ->"+list.get(0));
            }
        });

        Thread consumer = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    synchronized (OBJECT) {
                        if (hasRes) {
                            consume();
                            OBJECT.notify();
                            hasRes = false;
                        } else {
                            try {
                                OBJECT.wait();
                            } catch (Exception e) {
                            }
                        }
                    }
                }
            }

            private void consume() {
                Object o = list.get(0);
                Object remove = list.remove(0);
                System.out.println("consume->"+o);
            }
        });
        producer.start();
        consumer.start();


    }

}
